package com.leectrl.controller;

import android.content.SharedPreferences;
import android.os.Build;
import android.os.Message;

import androidx.annotation.RequiresApi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hdl.school.application.MyApplication;
import com.hdl.school.bean.CardInfo;
import com.hdl.school.bean.DeviceLog;
import com.hdl.school.bean.NetworkInfo;
import com.hdl.school.bean.RoomEventAction;
import com.hdl.school.bean.User;
import com.hdl.school.utils.Constants;
import com.hdl.school.utils.DeviceLogUtil;
import com.hdl.school.utils.Logger;
import com.hdl.school.utils.TCWManager;
import com.hdl.school.utils.TimeUtil;
import com.leectrl.utils.Bus;
import com.leectrl.utils.DbUtil;
import com.leectrl.utils.LocalCacheManage;
import com.leectrl.utils.RequestBody;
import com.leectrl.utils.RequestMapping;
import com.leectrl.utils.RequestParams;
import com.leectrl.utils.ResponseUtil;
import com.leectrl.utils.SCaptcha;
import com.likong.iotsdk.DeviceType;
import com.likong.iotsdk.RoomInfo;

import org.springframework.util.StringUtils;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.net.URLDecoder;
import java.util.List;
import java.util.UUID;

import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.util.internal.StringUtil;

public class ApiController {
    @RequestMapping(uri = "/sys/captcha/gen", method = "GET", auth = false)
    public String genCaptcha(@RequestParams(name = "code") String code) {
        SCaptcha sCaptcha = new SCaptcha();
        String captchaCodeImage = sCaptcha.createCodeImageStr();
        LocalCacheManage localCacheManage = LocalCacheManage.getInstance();
        localCacheManage.set("captcha_" + code, sCaptcha.getCode().toLowerCase(), 40000);
        return captchaCodeImage;
    }

    @RequestMapping(uri = "/sys/login", method = "POST", auth = false)
    public JSONObject userLogin(@RequestBody JSONObject jsonObject) {
        String account = jsonObject.getString("account");
        String password = jsonObject.getString("password");
        String securityCode = jsonObject.getString("securityCode");
        String code = jsonObject.getString("code");
        if (StringUtil.isNullOrEmpty(account) || StringUtil.isNullOrEmpty(password) || StringUtil.isNullOrEmpty(securityCode) || StringUtil.isNullOrEmpty(code)) {
            return ResponseUtil.responseFailureMsg(-1, "缺少必要参数");
        }
        if (account.indexOf("=") >= 0) {
            return ResponseUtil.responseFailureMsg(-2, "账户包含非法字符");
        }
        String codeKey = "captcha_" + code;
        LocalCacheManage localCacheManage = LocalCacheManage.getInstance();
        String cacheValue = localCacheManage.get(codeKey);
        if (StringUtil.isNullOrEmpty(cacheValue) || (!cacheValue.equals(securityCode.toLowerCase()))) {
            return ResponseUtil.responseFailureMsg(-8, "验证码错误");
        }
        localCacheManage.delete(codeKey);
        String lockKey = "account_" + account;
        String lockInfo = localCacheManage.get(lockKey);
        if (!StringUtil.isNullOrEmpty(lockInfo)) {
            JSONObject lockObject = JSON.parseObject(lockInfo);
            if (lockObject.getIntValue("err") >= 3) {
                long dur = System.currentTimeMillis() - lockObject.getLongValue("time");
                if (dur < 600000) {
                    return ResponseUtil.responseFailureMsg(-30, "账户已在" + (dur / 60000 == 0 ? "刚刚" : dur / 60000 + "分钟前") + "被锁定10分钟");
                }
            }
        }
        try {
            User user = DbUtil.getInstance().selector(User.class).where("account", "=", account).and("delete_tag", "=", "0").findFirst();
            if (user == null || (!password.substring(6, password.length() - 6).equals(user.getPwd().substring(4, user.getPwd().length() - 5)))) {
                JSONObject userErr = new JSONObject();
                if (StringUtil.isNullOrEmpty(lockInfo)) {
                    userErr.put("err", 1);
                    userErr.put("time", System.currentTimeMillis());
                    localCacheManage.set(lockKey, JSON.toJSONString(userErr), 600000);
                } else {
                    JSONObject lockObject = JSON.parseObject(lockInfo);
                    int errNum = lockObject.getIntValue("err");
                    userErr.put("err", errNum + 1);
                    userErr.put("time", System.currentTimeMillis());
                    localCacheManage.set(lockKey, JSON.toJSONString(userErr), 600000);
                    if (errNum >= 3) {
                        return ResponseUtil.responseFailureMsg(-3, "账号密码不匹配,再连续输错2次账号将被锁定10分钟。");
                    }
                }
                return ResponseUtil.responseFailureMsg(-3, "账号密码不匹配,再连续输错" + (3 - userErr.getIntValue("err")) + "次账号将被锁定10分钟。");
            }
            String session = "";
            for (int i = 0; i < 20; i++) {
                session += String.valueOf((char) (97 + (int) (Math.random() * 26)));
            }
            JSONObject userSession = new JSONObject();
            userSession.put("session", session);
            userSession.put("level", user.getLevel());
            userSession.put("uname", user.getName());
            localCacheManage.set("session_" + user.getId(), JSON.toJSONString(userSession), 1200000);
            JSONObject loginInfo = new JSONObject();
            loginInfo.put("session", session);
            loginInfo.put("user_id", user.getId());
            loginInfo.put("user_name", user.getName());
            DeviceLogUtil.saveDeviceLog(new DeviceLog(1, 1, "用户登录：" + user.getName(), user.getId()));
            return ResponseUtil.responseSuccessMsg(loginInfo);
        } catch (DbException e) {
            e.printStackTrace();
        }

        return ResponseUtil.responseSuccessMsg();
    }

    @RequestMapping(uri = "/app/admin/session/check", method = "POST", auth = true)
    public JSONObject checkUserSession(@RequestBody JSONObject jsonObject) {
        return ResponseUtil.responseSuccessMsg();
    }


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @RequestMapping(uri = "/app/network/config/get", method = "GET", auth = true)
    public JSONObject loadNetworkConfig(@RequestBody JSONObject jsonObject) {
        NetworkInfo networkInfo = TCWManager.getInstance(MyApplication.myApplication).getNetworkInfo();
        JSONObject networkObj = new JSONObject();
        networkObj.put("ip", networkInfo.getIp());
        networkObj.put("getway", networkInfo.getGateway());
        networkObj.put("netmask", networkInfo.getNetmask());
        networkObj.put("dns", networkInfo.getDns());
        return ResponseUtil.responseSuccessMsg(networkObj);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @RequestMapping(uri = "/app/network/config/set", method = "POST", auth = true)
    public JSONObject saveNetworkConfig(@RequestBody JSONObject jsonObject) {
        Message message = new Message();
        message.what = 0;
        message.obj = jsonObject;
        MyApplication.myApplication.handler.sendMessage(message);
        return ResponseUtil.responseSuccessMsg();
    }

    @RequestMapping(uri = "/app/mqtt/config/save", method = "POST", auth = true)
    public JSONObject saveMqttConfig(@RequestBody JSONObject jsonObject) {
        SharedPreferences sharedPreferences = MyApplication.myApplication.getSharedPreferences("school_iot", 0);
        sharedPreferences.edit().putString("outerMqtt",JSON.toJSONString(jsonObject)).commit();
        return ResponseUtil.responseSuccessMsg();
    }


    @RequestMapping(uri = "/app/app/info/load", method = "GET", auth = true)
    public JSONObject loadAppInfo(@RequestBody JSONObject jsonObject) {
        JSONObject jsonObject1 = new JSONObject();
        SharedPreferences sharedPreferences = MyApplication.myApplication.getSharedPreferences("school_iot", 0);
        String appid = sharedPreferences.getString("APPID", null);
        String deviceid = sharedPreferences.getString("DEVICEID", null);
        if (deviceid == null) {
            deviceid = UUID.randomUUID().toString().replaceAll("-", "");
            sharedPreferences.edit().putString("DEVICEID", deviceid).commit();
        }
        if (appid == null) {
            sharedPreferences.edit().putString("APPID", "lt123gh5623").commit();
        }
        jsonObject1.put("appid", appid);
        jsonObject1.put("deviceid", deviceid);
        jsonObject1.put("cloudctrl", sharedPreferences.getBoolean("CLOUDCTRL",false));
        String mac = sharedPreferences.getString("computer_mac", "");
        jsonObject1.put("mac", mac);
        String customSysCode = sharedPreferences.getString("customSysCode", "");
        if(customSysCode.length()>0){
            jsonObject1.put("customSysCode", JSON.parseObject(customSysCode));
        }
        String outerMqtt=sharedPreferences.getString("outerMqtt",null);
        if(outerMqtt!=null){
            JSONObject mqttConfig=JSON.parseObject(outerMqtt);
            jsonObject1.put("mqtt", mqttConfig);
        }
        return ResponseUtil.responseSuccessMsg(jsonObject1);
    }

    @RequestMapping(uri = "/admin/app/info/update", method = "POST", auth = false)
    public JSONObject updateAppInfo(@RequestBody JSONObject jsonObject) {
        if (!jsonObject.containsKey("type")) {
            return ResponseUtil.responseFailureMsg(-1, "缺少必要参数");
        }
        int type = jsonObject.getIntValue("type");
        if(type<3){
            if (!jsonObject.containsKey("pwd")) {
                return ResponseUtil.responseFailureMsg(-1, "缺少必要参数");
            }
            String pwd=jsonObject.getString("pwd");
            if(!pwd.equals("ZHJS2022@")){
                return ResponseUtil.responseFailureMsg(-3, "密码错误");
            }
        }
        SharedPreferences sharedPreferences = MyApplication.myApplication.getSharedPreferences("school_iot", 0);
        switch (type) {
            case 1:
                if (jsonObject.containsKey("appid")) {
                    sharedPreferences.edit().putString("APPID", jsonObject.getString("appid"));
                }
                break;
            case 2:
                sharedPreferences.edit().putString("DEVICEID", UUID.randomUUID().toString().replaceAll("-", "")).commit();
                break;
            case 3:
                sharedPreferences.edit().putBoolean("CLOUDCTRL", jsonObject.getBooleanValue("cloudctrl")).commit();
                break;
        }

        JSONObject jsonObject1 = new JSONObject();
        String appid = sharedPreferences.getString("APPID", null);
        String deviceid = sharedPreferences.getString("DEVICEID", null);
        jsonObject1.put("appid", appid);
        jsonObject1.put("deviceid", deviceid);
        jsonObject1.put("cloudctrl", jsonObject.getBooleanValue("cloudctrl"));
        return ResponseUtil.responseSuccessMsg(jsonObject1);
    }

    @RequestMapping(uri = "/app/sys/reboot", method = "GET", auth = true)
    public JSONObject rebootSys(@RequestBody JSONObject jsonObject) {
        TCWManager.getInstance(MyApplication.myApplication).reboot();
        return ResponseUtil.responseSuccessMsg();
    }

    @RequestMapping(uri = "/app/server/config/get", method = "GET", auth = true)
    public JSONObject loadServerConfig(@RequestBody JSONObject jsonObject) {
        SharedPreferences sharedPreferences = MyApplication.myApplication.getSharedPreferences("school_iot", 0);
        String serverConfig = sharedPreferences.getString("serverConfig", null);
        if (StringUtil.isNullOrEmpty(serverConfig)) {
            return ResponseUtil.responseFailureMsg(-3, "无数据");
        }
        JSONObject resp = new JSONObject();
        resp.put("server", serverConfig);
        String roomInfo = sharedPreferences.getString("room_info", null);
        if (roomInfo != null) {
            RoomInfo roomInfo1 = JSON.parseObject(roomInfo, RoomInfo.class);
            resp.put("room_id", roomInfo1.getRoomId());
        }
        return ResponseUtil.responseSuccessMsg(resp);
    }

    @RequestMapping(uri = "/app/server/config/set", method = "POST", auth = true)
    public JSONObject saveServerConfig(@RequestBody JSONObject jsonObject) {
        SharedPreferences sharedPreferences = MyApplication.myApplication.getSharedPreferences("school_iot", 0);
        sharedPreferences.edit().putString("serverConfig", jsonObject.getString("serverip") + ":" + jsonObject.getString("serverport")).commit();
        return ResponseUtil.responseSuccessMsg();
    }

    @RequestMapping(uri = "/app/server/config/test", method = "POST", auth = true)
    public JSONObject testServerConfig(@RequestBody JSONObject jsonObject) {
        String serverip = jsonObject.getString("serverip");
        String serverport = jsonObject.getString("serverport");
        org.xutils.http.RequestParams params = new org.xutils.http.RequestParams();
        params.setUri("http://" + serverip + ":" + serverport + "/publicapi/terminal/sys/getTime");
        try {
            String result = x.http().getSync(params, String.class);
            Logger.e(result);
            return ResponseUtil.responseSuccessMsg();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return ResponseUtil.responseFailureMsg(-4, "服务器不通");
    }

    @RequestMapping(uri = "/app/device/type/load", method = "GET", auth = true)
    public JSONObject loadDeviceType(@RequestBody JSONObject jsonObject) {
        JSONObject obj = new JSONObject();
        obj.put("deviceType", DeviceType.DEVICETYPE_CONTROLLER.toString());
        obj.put("version", Constants.CONTROLLER_VERSION.toString());
        return ResponseUtil.responseSuccessMsg(obj);
    }

    @RequestMapping(uri = "/app/serialport/info/load", method = "GET", auth = true)
    public JSONObject loadSerialportInfo() {
        SharedPreferences sharedPreferences = MyApplication.myApplication.getSharedPreferences("school_iot", 0);
        String serialportConfig = sharedPreferences.getString("serialport", null);
        if (serialportConfig == null) {
            return ResponseUtil.responseFailureMsg(-3, "无数据");
        }
        JSONObject object = JSON.parseObject(serialportConfig);
        JSONObject info = new JSONObject();
        for (int i = 0; i <= 10; i++) {
            if (object.containsKey("serialUSB" + i)) {
                info.put("serialUSB" + i, object.getJSONObject("serialUSB" + i).getString("portName"));
                info.put("serialBaudRate" + i, object.getJSONObject("serialUSB" + i).getString("baudRate"));
            }
            if (object.containsKey("ttyS" + i)) {
                info.put("ttyS" + i, object.getJSONObject("ttyS" + i).getString("portName"));
                info.put("ttySBaudRate"+i, object.getJSONObject("ttyS" + i).getString("baudRate"));
            }
        }
        return ResponseUtil.responseSuccessMsg(info);
    }

    @RequestMapping(uri = "/app/serialport/info/save", method = "POST", auth = true)
    public JSONObject saveSerialportInfo(@RequestBody JSONObject jsonObject) {
        JSONObject info = new JSONObject();
        for (int i = 0; i <= 10; i++) {
            if (jsonObject.containsKey("serialUSB" + i)) {
                JSONObject json = new JSONObject();
                json.put("portName", jsonObject.getString("serialUSB" + i));
                json.put("baudRate", jsonObject.getString("serialBaudRate" + i));
                info.put("serialUSB" + i, json);
            }
            if (jsonObject.containsKey("ttyS" + i)) {
                JSONObject json = new JSONObject();
                json.put("portName", jsonObject.getString("ttyS" + i));
                json.put("baudRate", jsonObject.getString("ttySBaudRate" + i));
                info.put("ttyS" + i, json);
            }
        }
        SharedPreferences sharedPreferences = MyApplication.myApplication.getSharedPreferences("school_iot", 0);
        sharedPreferences.edit().putString("serialport", JSON.toJSONString(info)).commit();
        return ResponseUtil.responseSuccessMsg();
    }

    @RequestMapping(uri = "/app/sys/rooms/get", method = "GET", auth = true)
    public JSONArray loadRoomTree() {
        org.xutils.http.RequestParams params = new org.xutils.http.RequestParams();
        SharedPreferences sharedPreferences = MyApplication.myApplication.getSharedPreferences("school_iot", 0);
        String serverConfigStr = sharedPreferences.getString("serverConfig", null);
        if (serverConfigStr == null) {
            return null;
        }
        params.setUri("http://" + serverConfigStr + "/publicapi/terminal/room/tree/load");
        try {
            String result = x.http().getSync(params, String.class);
            return JSON.parseArray(result);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }


    @RequestMapping(uri = "/app/room/bind", method = "POST", auth = true)
    public JSONObject bindRoom(@RequestBody JSONObject jsonObject, FullHttpRequest fullHttpRequest) {
        RoomInfo roomInfo = new RoomInfo();
        roomInfo.setRoomId(jsonObject.getIntValue("room_id"));
        String roomName = URLDecoder.decode(jsonObject.getString("room_name"));
        roomInfo.setRoomName(roomName);
        SharedPreferences sharedPreferences = MyApplication.myApplication.getSharedPreferences("school_iot", 0);
        sharedPreferences.edit().putString("room_info", JSON.toJSONString(roomInfo)).commit();
        uploadDevInfoToServer(sharedPreferences, roomInfo.getRoomId());
        DeviceLogUtil.saveDeviceLog(new DeviceLog(1, 1, "绑定课室：" + roomName, 0));
        Bus.getInstance().emit("room_binded", roomInfo);
        return ResponseUtil.responseSuccessMsg();
    }


    @RequestMapping(uri = "/app/terminal/update", method = "POST", auth = true)
    public JSONObject updateTerminal(@RequestBody JSONObject jsonObject) {
        Message message=new Message();
        message.what=6;
        message.obj=jsonObject.getString("downloadUrl");
        MyApplication.myApplication.handler.sendMessage(message);
        return ResponseUtil.responseSuccessMsg();
    }

    @RequestMapping(uri = "/app/computer/mac", method = "POST", auth = true)
    public JSONObject saveComputerMac(@RequestBody JSONObject jsonObject) {

        SharedPreferences sharedPreferences = MyApplication.myApplication.getSharedPreferences("school_iot", 0);
        sharedPreferences.edit().putString("computer_mac", jsonObject.getString("mac")).commit();
        return ResponseUtil.responseSuccessMsg();
    }

    @RequestMapping(uri = "/app/sys/code/custom", method = "POST", auth = true)
    public JSONObject saveCustomSysCode(@RequestBody JSONObject jsonObject) {
        SharedPreferences sharedPreferences = MyApplication.myApplication.getSharedPreferences("school_iot", 0);
        sharedPreferences.edit().putString("customSysCode", JSON.toJSONString(jsonObject)).commit();
        return ResponseUtil.responseSuccessMsg();
    }

    private void uploadDevInfoToServer(SharedPreferences sharedPreferences, int roomId) {
        String serverConfig = sharedPreferences.getString("serverConfig", null);
        //获取网络信息
        org.xutils.http.RequestParams params = new org.xutils.http.RequestParams();
        params.setUri("http://" + serverConfig + "/publicapi/terminal/network/info/upload");
        NetworkInfo networkInfo = TCWManager.getInstance(MyApplication.getAppContext()).getNetworkInfo();
        params.addParameter("mac", networkInfo.getMac());
        params.addParameter("room_id", roomId);
        params.addParameter("dev_id", DeviceType.DEVICETYPE_CONTROLLER.toString());
        try {
            x.http().getSync(params, String.class);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }

    @RequestMapping(uri = "/app/room/info", method = "POST", auth = true)
    public JSONObject loadRoomInfo(@RequestBody JSONObject jsonObject) {
        SharedPreferences sharedPreferences = MyApplication.myApplication.getSharedPreferences("school_iot", 0);
        String roomInfoStr = sharedPreferences.getString("room_info", null);
        if (roomInfoStr == null) {
            return ResponseUtil.responseFailureMsg(-3, "未找到课室信息");
        }
        RoomInfo roomInfo = JSON.parseObject(roomInfoStr, RoomInfo.class);
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("data", roomInfo.getRoomName());
        return ResponseUtil.responseSuccessMsg(JSON.toJSONString(jsonObject1));
    }

    @RequestMapping(uri = "/card/info", method = "POST", auth = false)
    public JSONObject loadCardList(@RequestBody JSONObject jsonObject) {
        JSONArray ja = new JSONArray();
        try {
            int limit = jsonObject.getIntValue("limit");
            int page = jsonObject.getIntValue("page");
            List<CardInfo> cardInfos = DbUtil.getInstance().selector(CardInfo.class).offset((page - 1) * limit).limit(limit).findAll();
            for (CardInfo cardInfo : cardInfos) {
                JSONObject userObject = new JSONObject();
                userObject.put("card_type", cardInfo.getCardType());
                userObject.put("sex", cardInfo.getSex());
                userObject.put("name", cardInfo.getName());
                userObject.put("add_time", TimeUtil.date2String(cardInfo.getCreateTime(), null));
                userObject.put("card_num", cardInfo.getCardNum());
                userObject.put("department", cardInfo.getDepartment());
                userObject.put("position", cardInfo.getPosition());
                ja.add(userObject);
            }
            long count = DbUtil.getInstance().selector(CardInfo.class).count();
            return ResponseUtil.responseSuccessTableList(ja, (int) count);
        } catch (DbException e) {
            e.printStackTrace();
        }
        return ResponseUtil.responseFailureMsg(-7, "加载失败");
    }

    @RequestMapping(uri = "/card/his", method = "POST", auth = false)
    public JSONObject loadCreditRecordList(@RequestBody JSONObject jsonObject) {
        JSONArray ja = new JSONArray();
        try {
            int limit = jsonObject.getIntValue("limit");
            int page = jsonObject.getIntValue("page");
            List<CardInfo> cardInfos = DbUtil.getInstance().findAll(CardInfo.class);
            List<RoomEventAction> roomEventActions = DbUtil.getInstance().selector(RoomEventAction.class).offset((page - 1) * limit).limit(limit).findAll();
            for (RoomEventAction roomEventAction : roomEventActions) {
                JSONObject eventObject = new JSONObject();
                for (CardInfo cardInfo : cardInfos) {
                    if (cardInfo.getCardNum().equals(roomEventAction.getCardNum())) {
                        if (StringUtils.isEmpty(cardInfo.getName())) {
                            eventObject.put("name", "未命名人员");
                        } else {
                            eventObject.put("name", cardInfo.getName());
                        }
                        switch (cardInfo.getSex()) {
                            case 0:
                                eventObject.put("sexstr", "女");
                                break;
                            case 1:
                                eventObject.put("sexstr", "男");
                                break;
                            case 9:
                                eventObject.put("sexstr", "未登记");
                                break;
                        }
                        eventObject.put("department", cardInfo.getDepartment());
                        eventObject.put("position", cardInfo.getPosition());
                        break;
                    }
                }

                eventObject.put("event_time", TimeUtil.date2String(roomEventAction.getEventTime(), null));
                eventObject.put("card_num", roomEventAction.getCardNum());
                ja.add(eventObject);
            }
            long count = DbUtil.getInstance().selector(RoomEventAction.class).count();
            return ResponseUtil.responseSuccessTableList(ja, (int) count);
        } catch (DbException e) {
            e.printStackTrace();
        }
        return ResponseUtil.responseFailureMsg(-7, "加载失败");
    }

    @RequestMapping(uri = "/log/list", method = "POST", auth = false)
    public JSONObject loadEventLogList(@RequestBody JSONObject jsonObject) {
        JSONArray ja = new JSONArray();
        try {
            if ((!jsonObject.containsKey("limit")) || (!jsonObject.containsKey("page"))) {
                return ResponseUtil.responseFailureMsg(-6, "缺少必要参数");
            }
            int limit = jsonObject.getIntValue("limit");
            int page = jsonObject.getIntValue("page");
            List<DeviceLog> logs = DbUtil.getInstance().selector(DeviceLog.class).offset((page - 1) * limit).limit(limit).orderBy("create_time", true).findAll();
            for (DeviceLog log : logs) {
                JSONObject logObject = new JSONObject();
                logObject.put("source_type", log.getSourceType());
                logObject.put("user", "管理员");
                logObject.put("desc", log.getDesc());
                logObject.put("event_type", log.getEventType());
                logObject.put("create_time", TimeUtil.date2String(log.getCreateTime()
                        , null));

                ja.add(logObject);
            }
            long count = DbUtil.getInstance().selector(DeviceLog.class).count();
            return ResponseUtil.responseSuccessTableList(ja, (int) count);
        } catch (DbException e) {
            e.printStackTrace();
        }
        return ResponseUtil.responseFailureMsg(-7, "加载失败");
    }

    @RequestMapping(uri = "/user/admin/list", method = "POST", auth = true)
    public JSONObject loadAdminList(@RequestBody JSONObject jsonObject, FullHttpRequest request, User currentUser) {
        HttpHeaders httpHeaders = request.headers();
        JSONArray ja = new JSONArray();
        try {
            if ((!jsonObject.containsKey("limit")) || (!jsonObject.containsKey("page"))) {
                return ResponseUtil.responseFailureMsg(-6, "缺少必要参数");
            }
            int limit = jsonObject.getIntValue("limit");
            int page = jsonObject.getIntValue("page");
            List<User> users = DbUtil.getInstance().selector(User.class).where("user_level", ">", currentUser.getLevel()).offset((page - 1) * limit).limit(limit).orderBy("create_time", true).findAll();
            for (User user : users) {
                JSONObject logObject = new JSONObject();
                logObject.put("name", user.getName());
                logObject.put("account", user.getAccount());
                logObject.put("rowid", user.getId());
                logObject.put("create_time", TimeUtil.date2String(user.getCreateTime()
                        , null));

                ja.add(logObject);
            }
            long count = DbUtil.getInstance().selector(DeviceLog.class).count();
            return ResponseUtil.responseSuccessTableList(ja, (int) count);
        } catch (DbException e) {
            e.printStackTrace();
        }
        return ResponseUtil.responseFailureMsg(-7, "加载失败");
    }

    @RequestMapping(uri = "/app/admin/exit", method = "POST", auth = true)
    public JSONObject exitApp(FullHttpRequest request, User currentUser) {
        HttpHeaders httpHeaders = request.headers();
        String userid = httpHeaders.get("user_id");
        LocalCacheManage localCacheManage = LocalCacheManage.getInstance();
        localCacheManage.delete("session_" + userid);
        DeviceLogUtil.saveDeviceLog(new DeviceLog(1, 1, "用户退出登录：" + currentUser.getName(), currentUser.getId()));
        return ResponseUtil.responseSuccessMsg();
    }


}
